﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.Vehicle.Dto;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
namespace Admin.NET.Application;

/// <summary>
/// 车辆信息表服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class VehicleService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Vehicle> _vehicleRep;
    public VehicleService(SqlSugarRepository<Vehicle> vehicleRep)
    {
        _vehicleRep = vehicleRep;
    }

    /// <summary>
    /// 分页查询车辆信息表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询车辆信息表")]
    public async Task<SqlSugarPagedList<VehicleOutput>> Page(PageVehicleInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _vehicleRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.VehicleNo.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.VehicleNo), u => u.VehicleNo.Contains(input.VehicleNo.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<OccupantAudit>((u, peopleid) => u.PeopleId == peopleid.Id)
            .LeftJoin<Community>((u, peopleid, roomid) => u.RoomId == roomid.Id)
            .LeftJoin<Stall>((u, peopleid, roomid, stallid) => u.StallId == stallid.Id)
            .WhereIF(!string.IsNullOrWhiteSpace(input.PeopleIdOccupantName), (u, peopleid) => peopleid.OccupantName.Contains(input.PeopleIdOccupantName))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OccupantPhone), (u, peopleid) => peopleid.OccupantPhone.Contains(input.OccupantPhone))
            .Select((u, peopleid, roomid, stallid) => new VehicleOutput
            {
                Id = u.Id,
                PeopleId = u.PeopleId,
                PeopleIdId = peopleid.Id,
                PeopleIdOccupantName = peopleid.OccupantName,
                OccupantPhone = peopleid.OccupantPhone,
                OccupantExpirationTime = peopleid.OccupantExpirationTime,
                StallId = u.StallId,
                StallIdId = stallid.Id,
                StopCarMoney = stallid.StopCarMoney,
                Operation = stallid.Operation,
                CarState = stallid.CarState,
                CarNo = stallid.CarNo,
                RoomId = u.RoomId,
                RoomIdId = roomid.Id,
                CommunityName = roomid.CommunityName,
                VehicleNo = u.VehicleNo,
                VehicleModel = u.VehicleModel,
                VehicleColor = u.VehicleColor,
                VehicleCard = u.VehicleCard,
                VehicleState = u.VehicleState,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加车辆信息表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加车辆信息表")]
    public async Task<long> Add(AddVehicleInput input)
    {
        var entity = input.Adapt<Vehicle>();
        await _vehicleRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除车辆信息表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除车辆信息表")]
    public async Task Delete(DeleteVehicleInput input)
    {
        var entity = await _vehicleRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _vehicleRep.FakeDeleteAsync(entity);   //假删除
        //await _vehicleRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新车辆信息表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新车辆信息表")]
    public async Task Update(UpdateVehicleInput input)
    {
        var entity = input.Adapt<Vehicle>();
        await _vehicleRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取车辆信息表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取车辆信息表")]
    public async Task<VehicleByDto> Detail([FromQuery] QueryByIdVehicleInput input)
    {
        var query = await _vehicleRep.AsQueryable()
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<OccupantAudit>((u, peopleid) => u.PeopleId == peopleid.Id)
            .LeftJoin<Community>((u, peopleid, roomid) => u.RoomId == roomid.Id)
            .LeftJoin<Stall>((u, peopleid, roomid, stallid) => u.StallId == stallid.Id)
            .Select((u, peopleid, roomid, stallid) => new VehicleByDto
            {
                Id = u.Id,
                PeopleId = u.PeopleId,
                PeopleIdId = peopleid.Id,
                OccupantNo = peopleid.OccupantNo,
                PeopleIdOccupantName = peopleid.OccupantName,
                OccupantPhone = peopleid.OccupantPhone,
                OccupantExpirationTime = peopleid.OccupantExpirationTime,
                StallId = u.StallId,
                StallIdId = stallid.Id,
                StopCarMoney = stallid.StopCarMoney,
                Operation = stallid.Operation,
                CarState = stallid.CarState,
                CarNo = stallid.CarNo,
                RoomId = u.RoomId,
                RoomIdId = roomid.Id,
                CommunityName = roomid.CommunityName,
                VehicleNo = u.VehicleNo,
                VehicleModel = u.VehicleModel,
                VehicleColor = u.VehicleColor,
                VehicleCard = u.VehicleCard,
                VehicleState = u.VehicleState,
            }).FirstAsync(u => u.Id == input.Id);
        return query;
    }
    //public async Task<Vehicle> Detail([FromQuery] QueryByIdVehicleInput input)
    //{
    //    return await _vehicleRep.GetFirstAsync(u => u.Id == input.Id);
    //}

    /// <summary>
    /// 获取车辆信息表列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取车辆信息表列表")]
    public async Task<List<VehicleOutput>> List([FromQuery] PageVehicleInput input)
    {
        return await _vehicleRep.AsQueryable().Select<VehicleOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取人员管理Id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "OccupantAuditPeopleIdDropdown"), HttpGet]
    [DisplayName("获取人员管理Id列表")]
    public async Task<dynamic> OccupantAuditPeopleIdDropdown()
    {
        return await _vehicleRep.Context.Queryable<OccupantAudit>()
                .Select(u => new
                {
                    Label = u.Id,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取车位Id列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "StallStallIdDropdown"), HttpGet]
    [DisplayName("获取车位Id列表")]
    public async Task<dynamic> StallStallIdDropdown()
    {
        return await _vehicleRep.Context.Queryable<Stall>()
                .Select(u => new
                {
                    Label = u.Id,
                    Value = u.Id
                }
                ).ToListAsync();
    }



}
